package com.example.book.api;

import com.example.book.base.ApiBaseController;
import com.example.book.base.Result;
import com.example.book.common.annotation.LoginIgnore;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.wx.UserInfo;
import com.example.book.in.entity.*;
import com.example.book.in.service.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
public class ApiBookController extends ApiBaseController {


    private BookInfoService bookInfoService;
    private BookCategoryService bookCategoryService;
    private BookPopularityService bookPopularityService;
    private BookCatalogService catalogService;
    private RedisService redisService;
    private UserBookshelfService bookshelfService;
    private UserReadRecordService readRecordService;

    private ApiBookController(BookInfoService bookInfoService, BookCategoryService bookCategoryService, BookPopularityService bookPopularityService
            , BookCatalogService catalogService, RedisService redisService, UserBookshelfService bookshelfService, UserReadRecordService readRecordService) {
        this.bookInfoService = bookInfoService;
        this.bookCategoryService = bookCategoryService;
        this.bookPopularityService = bookPopularityService;
        this.catalogService = catalogService;
        this.redisService = redisService;
        this.bookshelfService = bookshelfService;
        this.readRecordService = readRecordService;
    }


    /**
     * 首页10条随机完本推荐
     *
     * @return
     */
    @GetMapping("/end/list")
    @LoginIgnore
    public Result findEndBookByRand() {
        List<BookInfo> bookInfos = bookInfoService.findEndBookByRand(10);

        Map<String, Object> map = null;
        BookCategory category = new BookCategory();
        List<Map<String, Object>> list = new ArrayList<>();
        for (BookInfo bi : bookInfos) {
            map = new HashMap<>();
            map.put("id", bi.getId());
            map.put("picture", picture_url + bi.getBookCover());

            category.setId(bi.getCategoryId());
            BookCategory bc = bookCategoryService.get(category);
            if (bc != null) {
                map.put("category", bc.getName());
            } else {
                map.put("category", "未分类");
            }

            if (bi.getBookName().length() > 11) {
                String idt = bi.getBookName().substring(0, 11) + "...";
                map.put("name", idt);
            } else {
                map.put("name", bi.getBookName());
            }
            map.put("author", bi.getBookAuthor().replace("作者：", ""));

            if (bi.getBookIntroduction().length() > 46) {
                String idt = bi.getBookIntroduction().substring(0, 46) + "...";
                map.put("introduction", idt);
            } else {
                if (StringUtils.isBlank(bi.getBookIntroduction())) {
                    map.put("introduction", "^^...");
                } else {
                    map.put("introduction", bi.getBookIntroduction());
                }
            }

            // 人气
            BookPopularity bookPopularity = new BookPopularity();
            bookPopularity.setBookInfoId(bi.getId());
            List<BookPopularity> popularities = bookPopularityService.findList(bookPopularity);
            map.put("popularity", popularities.size());

            list.add(map);
        }
        if (list.size() < 1) {
            return Result.error();
        }
        return Result.success(list);
    }

    /**
     * 检索页面查询书籍信息的分页方法
     *
     * @param bookInfo
     * @return
     */
    @PostMapping("/popular/searches/list")
    @LoginIgnore
    public Result selectPopularSearchesList(BookInfo bookInfo) {
        // 模糊分页搜索
        PageInfo<BookInfo> pageInfo = bookInfoService.findListBySearch(bookInfo);
        Map<String, Object> map = null;
        BookCategory category = new BookCategory();
        List<Map<String, Object>> list = new ArrayList<>();
        for (BookInfo bi : pageInfo.getList()) {
            map = new HashMap<>();
            map.put("id", bi.getId());
            map.put("picture", picture_url + bi.getBookCover());

            category.setId(bi.getCategoryId());
            BookCategory bc = bookCategoryService.get(category);
            if (bc != null) {
                map.put("category", bc.getName());
            } else {
                map.put("category", "未分类");
            }

            if (bi.getBookName().length() > 11) {
                String idt = bi.getBookName().substring(0, 11) + "...";
                map.put("name", idt);
            } else {
                map.put("name", bi.getBookName());
            }
            map.put("author", bi.getBookAuthor().replace("作者：", ""));

            if (bi.getBookIntroduction().length() > 46) {
                String idt = bi.getBookIntroduction().substring(0, 46) + "...";
                map.put("introduction", idt);
            } else {
                if (StringUtils.isBlank(bi.getBookIntroduction())) {
                    map.put("introduction", "^^...");
                } else {
                    map.put("introduction", bi.getBookIntroduction());
                }
            }

            // 人气
            BookPopularity bookPopularity = new BookPopularity();
            bookPopularity.setBookInfoId(bi.getId());
            List<BookPopularity> popularities = bookPopularityService.findList(bookPopularity);
            map.put("popularity", popularities.size());

            list.add(map);
        }

        Map<String, Object> map1 = new HashMap<>();
        map1.put("isHasNextPage", pageInfo.isHasNextPage());
        map1.put("data", list);

        return Result.success("success", map1);
    }

    /**
     * 热门搜索 文字、id推荐
     *
     * @param info
     * @return
     */
    @GetMapping("/popular/searches")
    @LoginIgnore
    public Result selectPopularSearches(BookInfo info) {
        List<BookInfo> list = bookInfoService.selectPopularSearches(6);
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = null;
        for (BookInfo bi : list) {
            map = new HashMap<>();
            map.put("id", bi.getId());
            map.put("text", bi.getBookName());
            mapList.add(map);
        }
        return Result.success("success", mapList);
    }

    /**
     * 获取书籍详情信息
     *
     * @param info
     * @return
     */
    @GetMapping("/info")
    @LoginIgnore
    public Result getDetails(BookInfo info) {

        BookInfo bi = bookInfoService.get(info);
        if (bi == null) {
            return Result.error();
        }

        Map<String, Object> map = new HashMap<>();

        // 书籍信息
        map.put("id", bi.getId());
        map.put("picture", picture_url + bi.getBookCover());
        map.put("name", bi.getBookName());
        map.put("author", bi.getBookAuthor().replace("作者：", ""));

        if (StringUtils.isBlank(bi.getBookIntroduction())) {
            map.put("introduction", "^^...");
        } else {
            map.put("introduction", bi.getBookIntroduction());
        }

        // 阅读数统计
        UserReadRecord readRecord = new UserReadRecord();
        readRecord.setBookInfoId(bi.getId());
        List<UserReadRecord> recordList = readRecordService.selectReadRecord(readRecord);
        map.put("readRecord", recordList.size());
        // 人气
        BookPopularity popularity = new BookPopularity();
        popularity.setBookInfoId(bi.getId());
        List<BookPopularity> bp = bookPopularityService.findList(popularity);
        map.put("popularity", bp.size());

        // 分类信息
        BookCategory bc = new BookCategory();
        bc.setId(bi.getCategoryId());
        BookCategory category = bookCategoryService.get(bc);
        map.put("category", category.getName());

        // 查询书籍目录
        BookCatalog catalog = new BookCatalog();
        catalog.setBookInfoId(bi.getId());
        BookCatalog bookCatalog = catalogService.selectOrderByIndexDesc(catalog);
        if (bookCatalog == null) {
            map.put("catalogIndex", "0");
            map.put("updataTime", "0");
        } else {
            map.put("catalogIndex", bookCatalog.getCatalogIndex());
            map.put("updataTime", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(bookCatalog.getCreateDate()));
        }

        // 判断是否加入书架
        String token = getToken();
        if (StringUtils.isNotBlank(token)) {
            UserInfo userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
            if (userInfo == null) {
                map.put("bookshelf", false);
            } else {
                UserBookshelf bookshelf = new UserBookshelf();
                bookshelf.setUserId(userInfo.getUid());
                bookshelf.setBookInfoId(bi.getId());
                UserBookshelf ub = bookshelfService.get(bookshelf);
                if (ub == null) {
                    map.put("bookshelf", false);
                } else {
                    map.put("bookshelf", true);
                }
            }
        } else {
            map.put("bookshelf", false);
        }
        return Result.success(map);
    }


    /**
     * 按分类加载书籍信息
     *
     * @param bookInfo
     * @return
     */
    @GetMapping
    @LoginIgnore
    public Result getCategory(BookInfo bookInfo) {

        BookCategory bc = new BookCategory();
        bc.setId(bookInfo.getCategoryId());
        BookCategory category = bookCategoryService.get(bc);

        // 只查询上架的书籍
        bookInfo.setStatus("1");
        //设置flag=1 表示查询有书籍目录的书
        bookInfo.setFlag("1");
        PageInfo<BookInfo> pageInfo = bookInfoService.findPage(bookInfo);

        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = null;
        for (BookInfo bi : pageInfo.getList()) {
            map = new HashMap<>();
            map.put("id", bi.getId());

            if (bi.getBookName().length() > 11) {
                String idt = bi.getBookName().substring(0, 11) + "...";
                map.put("name", idt);
            } else {
                map.put("name", bi.getBookName());
            }

            map.put("picture", picture_url + bi.getBookCover());
            map.put("category", category.getName());

            map.put("author", bi.getBookAuthor().replace("作者：", ""));

            if (bi.getBookIntroduction().length() > 46) {
                String idt = bi.getBookIntroduction().substring(0, 46) + "...";
                map.put("introduction", idt);
            } else {
                if (StringUtils.isBlank(bi.getBookIntroduction())) {
                    map.put("introduction", "^^...");
                } else {
                    map.put("introduction", bi.getBookIntroduction());
                }
            }

            // 人气
            BookPopularity popularity = new BookPopularity();
            popularity.setBookInfoId(bi.getId());
            List<BookPopularity> bp = bookPopularityService.findList(popularity);
            map.put("popularity", bp.size());

            list.add(map);
        }

        if (list.size() < 1) {
            return Result.error("no data");
        }

        Map<String, Object> map1 = new HashMap<>();

        map1.put("list", list);
        map1.put("isHasNextPage", pageInfo.isHasNextPage());

        return Result.success(map1);
    }

}
